<template>
  <el-tooltip
    class="t-tooltip"
    effect="light"
    :content="tooltip"
    placement="right-end"
    :disabled="toolDisabled"
  >
    <el-select
      v-model="value"
      @change="changeSelect"
      @visible-change="visibleChange"
      :multiple="isMultiple"
      collapse-tags
      :value-key="config.valueKey ? config.valueKey : 'id'"
      size="mini"
      ref="tSelect"
      popper-class="t-select"
      placeholder="请选择"
      clearable
      filterable
      :disabled="disabled"
    >
      <!-- 表头 -->
      <div class="t-table-header">
        <table
          cellspacing="0"
          cellpadding="0"
          border="0"
          class="t-table-wrapper"
          style="width: 100%"
        >
          <thead>
            <tr>
              <th
                v-for="(item, index) in columns"
                :key="index"
                class="t-th"
                :style="{
                  minWidth: item.minWidth || '100px',
                  width: item.width || '100px'
                }"
              >
                <div class="t-header-txt">{{ item.label }}</div>
                <el-input
                  placeholder="请输入"
                  v-model="searchList[item.prop]"
                  @change="changeInput(searchList[item.prop], item.prop)"
                  clearable
                  size="mini"
                  class="t-header-input"
                >
                </el-input>
              </th>
            </tr>
          </thead>
        </table>
      </div>
      <div class="t-select-option">
        <el-option
          v-for="item in tableData"
          :key="item.id"
          :label="item[config.label ? config.label : 'name']"
          :value="item"
          class="select_option"
        >
          <table
            cellspacing="0"
            cellpadding="0"
            border="0"
            class="t-table-wrapper"
            style="width: 100%"
          >
            <tr class="t-tr">
              <td
                class="t-ceil"
                :style="{
                  minWidth: child.minWidth || '100px',
                  width: child.width || '100px'
                }"
                v-for="(child, j) in columns"
                :key="j"
              >
                {{ item[child.prop] }}
              </td>
            </tr>
          </table>
        </el-option>
      </div>
      <template #empty v-if="tableData.length <= 0">
        <div class="empty-box">
          <!-- 无匹配数据 -->
          <span>暂无匹配数据</span>
          <!-- 点击重新加载 -->
          <span class="load-text" @click="reGetDataList">点击重新加载</span>
        </div>
      </template>
      <div class="t-bottom-page" v-if="isShowPagination">
        <el-pagination
          small
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :pager-count="pagerCount"
        >
        </el-pagination>
        <!-- 重新获取数据 -->
        <div class="pag-tip" @click="reGetDataList" v-if="showBtn">重新获取数据</div>
      </div>
    </el-select>
  </el-tooltip>
</template>

<script>
import { deepClone } from "@/utils/index";
export default {
  props: {
    /**
     * @desc 配置
     * @params valueKey: 下拉框多选对象, 默认id
     *         label: 用于选中后展示的选项, 默认name
     *         checkedList: 已选数组,为value的数组集合
     */
    config: {
      type: Object,
      default: () => {
        return {
          valueKey: "id",
          label: "name",
          isValueKey: true,
          checkedList: [],
        };
      },
    },
    /**
     * 列名
     */
    columns: {
      type: Array,
      default: () => {
        return [
          {
            prop: "number",
            label: "文件编号",
          },
          {
            prop: "name",
            label: "文件名称",
          },
          {
            prop: "efilename",
            label: "档案类型",
          },
          {
            prop: "typename",
            label: "文件类型",
          },
          {
            prop: "version",
            label: "版本",
          },
        ];
      },
    },
    /**
     * 表格内容
     */
    tableData: {
      type: Array,
      default: () => {
        return [
          {
            id: 1,
            number: "001",
            name: "测试文档",
            efilename: "纸质档",
            typename: "其他",
            version: "1.0",
          },
          {
            id: 2,
            number: "002",
            name: "测试文档2",
            efilename: "电子档",
            typename: "技术单",
            version: "2.0",
          },
          {
            id: 3,
            number: "003",
            name: "测试文档3",
            efilename: "电子档",
            typename: "技术单",
            version: "2.1",
          },
        ];
      },
    },
    // 总页数
    total: {
      type: Number,
      default: 0,
    },
    // 是否多选
    isMultiple: {
      type: Boolean,
      default: false,
    },
    // 开启分页
    isShowPagination: {
      type: Boolean,
      default: true,
    },
    // 是否可选
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      value: [], // 选中的值
      selectionArray: [], // 已选数组
      searchList: [], // 搜索数组
      currentPage: 1, // 当前页
      pageSize: 10, // 分页数
      pagerCount: 5, // 当超过多少页后分页
      isCollapseTags: false, // 是否折叠tags
      tooltip: "",
      showBtn: false, // 是否展示最后的获取表格提示
      // disabled: false, // 是否需要disabled
    };
  },
  computed: {
    // 不展示提示框的情况: 单选,下拉框展示,tooltip不为空
    toolDisabled() {
      let flag = !this.isMultiple || this.isCollapseTags || !this.tooltip
      return flag;
    },
  },
  watch: {
    tableData: {
      deep: true,
      immediate: true,
      handler() {},
    },
    config: {
      deep: true,
      immediate: true,
      handler(v) {
        if (v.checkedList && v.checkedList.length > 0) {
          this.init();
        }
      },
    },
    total: {
      deep: true,
      immediate: true,
      handler() {},
    },
  },
  created() {
    // this.config.valueKey = this.config.valueKey ? this.config.valueKey : "id";
    // this.config.isValueKey = this.config.isValueKey ? this.config.isValueKey : true;
    // this.init();
  },
  methods: {
    /**
     * 初始化加载数据
     */
    init() {
      this.config.valueKey = this.config.valueKey ? this.config.valueKey : "id";
      this.config.isValueKey = this.config.isValueKey
        ? this.config.isValueKey
        : true;
      let checkedList = this.config.checkedList;
      // 有默认选中值时的操作
      if (checkedList && checkedList.length > 0) {
        // 选中的是展示的label值
        if (!this.config.isValueKey) {
          this.tooltip = "";
          this.value = this.isMultiple ? [] : {};
          return;
        }
        // 默认选中的是绑定的value-key,如id
        let arr = [];
        // 单选的时候
        if (!this.isMultiple) {
          this.tableData.map((child) => {
            if (child[this.config.valueKey] === checkedList[0]) {
              this.value = deepClone(child);
              // this.searchList[this.columns[0].prop] = child[this.config.label];
              this.$set(
                this.searchList,
                this.columns[0].prop,
                child[this.config.label]
              );
              arr.push(child[this.config.label]);
            }
            return child[this.config.valueKey] === checkedList[0];
          });
        } else {
          // 多选
          this.showBtn = true;
          this.value = deepClone(checkedList);
          if (checkedList.length > 0) {
            checkedList.map((item) => {
              arr.push(item[this.config.label]);
            });
          }
          
          // checkedList.forEach((item) => {
          //   this.tableData.forEach((child) => {
          //     if (child[this.config.valueKey] === item) {
          //       this.value.push(child);
          //       arr.push(child[this.config.label]);
          //     }
          //   });
          // });
        }
        this.tooltip = arr.toString();
      }
    },
    reGetDataList() {
      this.showBtn = false;
      // this.value = [];
      this.searchList = [];
      this.$emit("inputChange", "", "", false);
    },
    /**
     * 格式化,置空
     */
    inEmpty() {
      this.value = [];
      this.searchList = [];
      // this.$emit("inputChange", "", "", false);
    },
    /**
     * 修改选择
     * 点击表格行后选择的表格行对象数组
     */
    changeSelect(arr) {
      this.$emit("selectChange", arr);
    },
    /**
     * 修改输入框 模糊搜索
     * params: val: 输入框的值;   prop: 表格对应列prop
     */
    changeInput(val, prop) {
      this.$emit("inputChange", val, prop, false);
    },
    // 下拉框出现/隐藏时触发	出现则为 true，隐藏则为 false
    visibleChange(val) {
      this.isCollapseTags = val;
      if (!val) {
        if (this.value.length > 0) {
          let arr = [];
          this.value.forEach((item) => {
            arr.push(item[this.config.label]);
          });
          this.tooltip = arr.toString();
        } else {
          this.tooltip = this.value[this.config.label];
        }
      }
    },
    // 每页数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1;
      this.$refs.tSelect.focus();
      this.$emit("sizeChange", this.currentPage, val);
    },
    // 当前页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.$emit("currentChange", val);
    },
  },
};
</script>

<style lang="scss" scope>
.limitHeigth {
  ::v-deep .el-select .el-input__inner {
    height: 28px !important;
  }
}
.t-tooltip {
  width: 100%;
}
.t-select {
  // 表头
  .t-table-header {
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
    height: 30px;
    font-size: 13px;
    font-weight: 600;
    z-index: 999;
    color: #515a6e;
    background-color: #f8f8f9;
    .t-table-wrapper {
      height: 100%;
      .t-th {
        border: 1px solid #dfe6ec !important;
        border-right: 0 !important;
        .t-header-txt:first-child {
          line-height: 25px;
          height: 25px;
          border-bottom: 1px solid #dfe6ec;
        }
        .t-header-input {
          .el-input__inner {
            padding: 0 10px;
          }
        }
      }
    }
  }
  // 表体
  .t-select-option {
    position: relative;
    top: 55px;
    margin-bottom: 55px;
  }
  .el-select-dropdown__wrap {
    max-height: 390px;
  }
  .el-select-dropdown__list {
    padding: 0;
    .select_option {
      padding: 0 !important;
      // border-bottom: 1px solid #dfe6ec;
      white-space: normal; // 换行
      word-wrap: break-word;
      text-overflow: initial;
      height: auto;
      line-height: 100%;
      vertical-align: middle;
      margin-bottom: -1px;
      .el-select-dropdown__item {
        padding: 0;
      }
      .t-ceil {
        height: 28px;
        text-align: center;
        line-height: 18px;
        border: 1px solid #dfe6ec;
        border-right: 0;
        &:first-child {
          border-left: 0;
        }
      }
    }
  }
  // 数据为空时的样式
  .empty-box {
    font-size: 12px;
    color: #c0c4cc;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 50px;
    .load-text {
      cursor: pointer;
      color: #409eff;
    }
  }
  // 表尾部(分页)
  .t-bottom-page {
    background-color: #f8f8f9;
    .el-pagination .el-select .el-input .el-input__inner {
      height: 22px;
    }
    .el-input__suffix {
      margin-top: 2px;
    }
    .pag-tip {
      text-align: center;
      font-size: 12px;
      color: #409eff;
      padding: 5px;
      cursor: pointer;
    }
  }
}
</style>
